package com.snts.synchronization.schema;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

public class Utils {

	public static boolean tableExists(DatabaseMetaData metadata, String schema,
			String tableName) throws SQLException {
		ResultSet rst = metadata.getTables(null, schema, tableName, null);
		try {
			return rst.next();
		} finally {
			rst.close();
		}

	}
	
	public static String evaluateTemplateFromResource(Class clazz, String resourceName, VelocityContext context) throws IOException {
		InputStream is = clazz.getResourceAsStream(resourceName);
		try {
			if (is == null) {
				throw new IOException("Resoure "
						+ clazz.getPackage().getName()
						+ '.' + resourceName
						+ " not found");
			}
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(is));
			try {
				StringWriter writer = new StringWriter();
				Velocity.setProperty("references.strict", "true");
				Velocity.evaluate(context, writer, "triggerGenerator", reader);
				return writer.toString();
			} finally {
				reader.close();
			}
		} finally {
			is.close();
		}
	}
	

}
